<template>
  <div>
    <!-- 质量报告审核 -->
    <TopFilter ref="TopFilters" :list="topFilterInit" :cols="3" :collapse="collapse" labelWidth="110" @filterChange="changeHandle"></TopFilter>
    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :params="fetchParams"
      :dataSource="dataList"
      :datakey="'records'"
      :fetchapi="fetchApi"
      :onColumnsChange="onColumnsChange"
      :onRowSelectChange="selectChange"
    >
      <template slot="controls">
        <multiuse-button :isShow="isDLR" size="small" type="primary" :click="handleAdd">新增</multiuse-button>
        <multiuse-button size="small" type="primary" :click="exportFileBtn.bind()" plain>导出</multiuse-button>
      </template>
    </FilterTable>

    <!-- 弹窗详情表单 -->
    <Drawer :visible.sync="editVisible" :title="setEditFormTitle" destroyOnClose width="60%" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <EditForm @close="editClose" @save="editSave" :rowData='editData'></EditForm>
    </Drawer>

     <!--  车辆选择 -->
    <BaseDialog :visible.sync="isShowCarDialog" title="车辆选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <VehicleChoice 
        @close="closeDialog('isShowCarDialog')" 
        @onConfirm="handleVehicleChoice" 
      />
      <!-- :vinOne="vinOne"  -->
    </BaseDialog>

     <!--  零件选择 -->
    <BaseDialog :visible.sync="isShowPartDialog" title="零件选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <PartChoice 
        @close="closeDialog('isShowPartDialog')" 
        @onConfirm="handlePartChoice" 
      />
    </BaseDialog>

    <img id="barcode" style="display: none" />
  </div>
</template>
<script>
import EditForm from './components/EditForm.vue';
import VehicleChoice from './components/VehicleChoice';
import PartChoice from './components/PartChoice';
import moment from 'moment';
import QRcode from 'qrcode';
import { exportExcelFile } from '@/utils/index';
import { getPartType } from '@/api/dictionary/index.js';
import { getListByPage, getListForExport, generateLabelPostList, exporturl } from '@/api/usedPartsReturnManage/usedPartsReturn_DLR/usedPartsWaitReturnQuery';
import JsBarcode from 'jsbarcode';
import { dictionary } from '@/utils/dictMixin';
import { getAppId } from '@/assets/js/auth';
// mock 方法
import mockFun from "@/mock/fun"
const { mockList } = mockFun.qualityManage.mockFunWrap() // 涉及闭包 所以需要先调用外层函数一次 然后通过解构获取对应mock方法

import {mapGetters,mapMutations} from 'vuex'
export default {
  name: 'qualityManage',
  mixins: [dictionary],
  components: {
    EditForm,
    VehicleChoice,
    PartChoice
  },
  props: {
    // 筛选条件 需要隐藏的字段名
    hideFilterStrArr: {
      type: Array,
      default: () => [''] // ['str1' , 'str2']
    },
  },
  data() {
    return {
      // 筛选条件数据源
      topFilterInit: this.topFilterInitFun(),
      // 列表数据源
      columns: this.creatHeader(),
      // 非单个禁用
      // single: true,
      single: false,
      // 非多个禁用
      multiple: true,
      dataList: [],
      editVisible: false,
      collapse: true,
      fetchApi: mockList,//getListByPage,
      fetchParams: { 
        // returnType : 55851001,
        beginApplyAt: moment()
          .month(moment().month())
          .startOf('month')
          .format('YYYY-MM-DD HH:mm:ss'),
        endApplyAt: moment()
          .month(moment().month())
          .endOf('month')
          .format('YYYY-MM-DD HH:mm:ss'),
        /**
         * 设为 false， mock逻辑接口才可正常
         */
        xhrAbort: false 
      }, //ipa 接口
      selectedRows: [], //选中经销商
      disableds: true,
      editData:{},// 当前编辑数据
      /**
       * 字段映射
       */
      statusMap:{
          DLR:{
            '50031001':'edit',
            '50031004':'edit',
          },
          OEM:{
            '50031001':'audit',
          }
      },
      btnValueMap:{
        edit:'编辑',
        audit: '审核' 
      }
    };
  },
  created() {
    this.fetchParams.beginApplyAt = moment()
      .startOf('week')
      .format('YYYY-MM-DD HH:mm:ss');
    this.fetchParams.endApplyAt = moment()
      .endOf('week')
      .format('YYYY-MM-DD HH:mm:ss');
  },
  computed:{
    ...mapGetters('qualityManage',['pageType','editFormStatus','isShowCarDialog','isShowPartDialog']),
    isDLR(){
      return this.pageType === 'DLR'
    },
    /**
     * 弹窗标题
     */
    setEditFormTitle(){
      const { editFormStatus } = this;
      const valMap = {
        readonly:'',
        add:'新增',
        ...this.btnValueMap
      }
      return `${valMap[editFormStatus]}质量报告`
    },
    
  },
  methods: {
    ...mapMutations('qualityManage',['SET_STATE_BY_NAME']),
    /**
     * 筛选条件配置
     */
    topFilterInitFun() {
      let data = [
        { type: 'INPUT', label: '质量报告单号', fieldName: 'reportNo', placeholder: '请输入质量报告单号', initialValue: '' },
        { type: 'INPUT', label: 'VIN', fieldName: 'vin', placeholder: '请输入VIN', initialValue: '' },
        {
          type: 'RANGE_DATE',
          label: '报告时间',
          fieldName: 'beginApplyAt|endApplyAt',
          placeholder: '请选择日期',
          initialValue: '',
          rules: [{ required: false, message: '请选择日期', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '单据状态',
          fieldName: 'reportStatus',
          placeholder: '请选择',
          initialValue: '',
          itemList: this.createDictList('5003')
        },
        { type: 'INPUT', label: '服务站', fieldName: 'dealerName', placeholder: '请输入服务站名称', initialValue: '' }
      ];

      // 过滤需要隐藏的筛选条件
      data = data.filter(item => !this.hideFilterStrArr.includes(item.fieldName));
      return data;
    },
    /**
     * table表头和数据源
     */
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 80,
          align: 'center',
          render: props => {
            const {getBtnValue,chooseOrderNo} = this
            const btnVal = getBtnValue(props.row)
            return (
              <div>
                <multiuse-button size="mini" type="text" onClick={() => chooseOrderNo(props.row,'readonly')}>
                  明细
                </multiuse-button>
                <multiuse-button isShow={Boolean(btnVal)} size="mini" type="text"  onClick={() => chooseOrderNo(props.row)}>
                  {btnVal} 
                </multiuse-button> 
              </div>
            );
          }
        },
        { title: '索赔单号', dataIndex: 'reportNo', sorter: false },
        {
          title: '单据状态',
          dataIndex: 'reportStatus',
          sorter: false,
          filterItems: this.createDictList('5003'),
          dictItems: this.createDictList('5003'),
          render: props => {
            return <span>{this.createDictText(props.row.reportStatus, '5003')}</span>;
          }
        },
        { title: '质量报告主题', dataIndex: 'caseMain', sorter: false },
        { title: 'VIN', dataIndex: 'vin', sorter: false, width: 150 },
        { title: '车牌', dataIndex: 'licensePlate', sorter: false },
        { title: '电机号', dataIndex: 'engineCode', sorter: false },
        { title: '车型', dataIndex: 'modelName', sorter: false },
        { title: '报告人', dataIndex: 'reporter', sorter: false },
        { title: '报告日期', dataIndex: 'applyAt', sorter: true, width: 140 }
      ];
    },
    /**
     * 通过 reportStatus 获取 详情表单状态标识（readonly、add、edit、audit）
     */
    getFromStatus(reportStatus){
      const { pageType , statusMap } = this
      // code(50031001) => status(edit)
      return statusMap[pageType][String(reportStatus)]
    },
    /**
     * 1.判断第二个按钮是否显示
     * 2.以及第二个操作按钮文案：（审核 || 编辑）
     */
    getBtnValue(item){
      const { btnValueMap, pageType, getFromStatus} = this
      const { reportStatus } = item

      // code(50031001) => status(edit) => 按钮字(编辑)
      const btnValue = btnValueMap[getFromStatus(reportStatus)]

      // 车  厂 DLR：已提报         才显示第二个按钮 【审核】
      // 经销商 OEM：已提报、已保存   才显示第二个按钮 【编辑】
      let isShow  = false;
      let status = []
      status = pageType === 'OEM' ? ['50031001'] :['50031001','50031004'];
      isShow = status.includes(String(reportStatus));
      return isShow ? btnValue : null
    },
    /**
     * 设置详情表单状态
     */
    setFromStatus(item,status){
      const { getFromStatus} = this
      const { reportStatus } = item

      const value = status || getFromStatus(reportStatus)
      // 状态有值才设置
      value && this.setStateParam('editFormStatus',value)
    },
    /**
     * 关闭弹窗
     */
    closeDialog(name){
      this.setStateParam(name,false)
    },
    /**
     * 修改 store 中的参数 name 为 value
     */
    setStateParam(name,value){
      const params = { name, value }
      this.SET_STATE_BY_NAME(params)
    },
    /**
     * 新增
     */
    handleAdd(){
      this.setStateParam('editFormStatus','add')
      this.editVisible = true;
    },
    /**
     * 车辆选择事件
     */
    handleVehicleChoice(e) {
      console.log('选中的车辆信息=>',e)
    },
    /**
     * 零件选择事件
     */
    handlePartChoice(e) {
      console.log('选中的零件信息=>',e)
    },
    onColumnsChange(columns) {
      this.columns = columns;
      this.single = columns.length != 1;
      this.multiple = !columns.length;
    },
    // 导出
    async exportFileBtn() {
      let json = Object.assign({}, { CODE: 'CODE_00000221' }, this.fetchParams);
      let res = await exporturl(json);
      if (res.resultCode == 200) {
        this.$router.push('/admin/auth/oem/downloadCenter');
      }
    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      this.disableds = this.selectedRows.length <= 0;
      console.log(this.selectedRows);
    },
    chooseOrderNo(val,status) {
      // 当前编辑数据
      this.editData = val;
      // 设置表单状态
      this.setFromStatus(val,status)
      this.editVisible = true;
    },
    editClose() {
      this.editVisible = false;
    },
    editSave() {
      this.editVisible = false;
      this.fetchParams = { ...this.fetchParams };
    },

    //搜索获取数据
    changeHandle(val) {
      if (!val.beginApplyAt) {
        this.$notify.warning({ title: '提示信息', message: '申请开始日期不可为空！' });
        return;
      }
      if (!val.endApplyAt) {
        this.$notify.warning({ title: '提示信息', message: '申请结束日期不可为空！' });
        return;
      }
      if (getAppId() == 'arcfox') {
        if (moment(moment(val.endApplyAt).format('YYYY-MM-DD')).diff(moment(val.beginApplyAt), 'months', true) > 12) {
          this.$notify.warning({ title: '提示信息', message: '申请日期跨度不可超过十二个月！' });
          return;
        }
      } else {
        if (moment(moment(val.endApplyAt).format('YYYY-MM-DD')).diff(moment(val.beginApplyAt), 'months', true) > 12) {
          this.$notify.warning({ title: '提示信息', message: '申请日期跨度不可超过十二个月！' });
          return;
        }
      }
      this.fetchParams = Object.assign({}, this.fetchParams, val, { xhrAbort: false });
      console.log(val);
    }
  }
};
</script>

<style lang="less" scoped></style>
